#include "pybackend.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
extern gchar* p_app;

gpointer thread_proxy(gpointer data)
{
	gint * _res = &data;
	*_res = 0;
	if((backend_pid = fork()) == 0){
		printf("Successful！\tSubprocess PID：%d\n", getpid());
		execlp("python", "python", p_app, (char *)0);
		perror("execlp Error:");
		exit(127);
	}
	else
	{
		printf("Parent's process PID：%d\n", getpid());
		gint t_pid;
		if((t_pid = wait(_res) ) > 0){
		kill(t_pid, SIGKILL);//如果执行成功的话线程已经全部转入后端，只有执行失败时才会执行该操作
		*_res = -1;
		}
	}
    g_thread_exit(NULL);
}

gboolean execute_backend(void){
//This part of Glib is a trash. Thus, I use the classical method.
/*	gchar* appargv[2];
	appargv[0] = "python";
	gchar* app = malloc(strlen(p_app)+1);
	strcpy(app, p_app);
	appargv[1] = app;
	gboolean r = g_spawn_async_with_pipes (NULL, appargv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, backend_pid, NULL, backend_output, NULL, &spawn_error);
	if(r)	return TRUE;
	else{
		perror("Execution failed");
		g_clear_error(&spawn_error);
		return FALSE;
	}
*/
	backend_pid = -1;
	thread_res = g_thread_create(thread_proxy, (gpointer)sub_res, FALSE, NULL);
	usleep(100000);//停顿0.1秒以获得sub_res的准确值
	if(sub_res != -1)	return TRUE;
	else	return FALSE;
}
void close_backend(){
	if(backend_pid > 0){
		kill(backend_pid, SIGKILL);
		backend_pid = -1;
	}
}
